package com.song.tools.core.util.excel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.song.tools.core.enums.StringCodeBaseEnum;
import lombok.NoArgsConstructor;

/**
 * 字符串枚举转换器
 *
 * @author song tools
 * @since 2024-06-27
 */
@NoArgsConstructor
public class StringCodeEnumConverter implements Converter<StringCodeBaseEnum> {

    public Class<?> supportJavaTypeKey() {
        return StringCodeBaseEnum.class;
    }

    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    public WriteCellData<?> convertToExcelData(StringCodeBaseEnum value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return new WriteCellData<>(value.getDesc());
    }

    public StringCodeBaseEnum convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        Class<? extends StringCodeBaseEnum> cls = (Class<? extends StringCodeBaseEnum>) contentProperty.getField().getType();
        if (cellData.getNumberValue() != null) {
            return StringCodeBaseEnum.convertDescToEnum(cellData.getNumberValue().toString(), cls);
        } else {
            return cellData.getStringValue() != null ? StringCodeBaseEnum.convertDescToEnum(cellData.getStringValue(), cls) : null;
        }
    }
}
